package com.rui.sideup.module.codegen.core.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

@Component
public class ThymeleafFacade {

    private static TemplateEngine textTemplateEngine;

    @Autowired
    public void setTextTemplateEngine(TemplateEngine textTemplateEngine) {
        ThymeleafFacade.textTemplateEngine = textTemplateEngine;
    }

    /**
     * 返回String
     * @param templateName
     * @param data
     * @return
     */
    public static String getResult(String templateName, Map<String, Object> data) {
        Context context = new Context();
        context.setVariables(data);
        String text = textTemplateEngine.process(templateName, context);
        return text;
    }

    /**
     * 直接写入文件
     * @param templateName
     * @param data
     * @param file
     */
    public static void getResult(String templateName, Map<String, Object> data, String file) throws IOException {
        Context context = new Context();
        context.setVariables(data);
        Writer writer = new FileWriter(file);
        textTemplateEngine.process(templateName, context, writer);
    }

}
